package com.demodis.dao.impl;

import java.util.ArrayList;
import java.util.List;

import com.demodis.dao.PositionDaoI;
import com.demodis.domain.TblPosition;
import com.demodis.util.DBUtil;

public class PositionDaoImpl extends BaseDao implements PositionDaoI {

	@Override
	public boolean save(TblPosition t) {
		String sql = "INSERT INTO TBL_POSITION(POSTGROUP, POSNAME, POSTYPE) VALUES(?, ?, ?);";
		int i = 0;
		try {
			conn = DBUtil.getConnection();
			ps = conn.prepareStatement(sql);

			ps.setInt(1, t.getPostGroup());
			ps.setString(2, t.getPosName());
			ps.setInt(3, t.getPosType());

			i = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return i == 1 ? true : false;
	}

	@Override
	public boolean delete(TblPosition t) {
		String sql = "DELETE FROM TBL_POSITION WHERE posId IN(" + t.getIds() + ");";
		int i = 0;
		try {
			conn = DBUtil.getConnection();

			ps = conn.prepareStatement(sql);
			i = ps.executeUpdate();

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return i > 0 ? true : false;
	}

	@Override
	public boolean modify(TblPosition t) {
		String sql = "UPDATE TBL_POSITION SET POSTGROUP = ?, POSNAME = ?, POSTYPE = ? WHERE POSID = ?;";
		int i = 0;
		try {
			conn = DBUtil.getConnection();
			ps = conn.prepareStatement(sql);

			ps.setInt(1, t.getPostGroup());
			ps.setString(2, t.getPosName());
			ps.setInt(3, t.getPosType());
			ps.setInt(4, t.getPosId());

			i = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, ps, rs);
		}

		return i == 1;
	}

	@Override
	public List<TblPosition> get() {
		String sql = "SELECT A.*, B.GROUPNAME FROM TBL_POSITION A, TBL_GROUP B WHERE A.POSTGROUP = B.GROUPID order by sort ASC;";
		List<TblPosition> list = new ArrayList<TblPosition>();
		try {
			conn = DBUtil.getConnection();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				TblPosition position = new TblPosition();
				position.setPosId(rs.getInt("posId"));
				position.setPostGroup(rs.getInt("postGroup"));
				position.setGroupName(rs.getString("groupName"));
				position.setPosName(rs.getString("posName"));
				position.setPosType(rs.getInt("posType"));
				list.add(position);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return list;
	}

	@Override
	public int getFirstPosId() {
		String sql = "SELECT posId FROM tbl_position LIMIT 1;";
		int posId = 0;
		try {
			conn = DBUtil.getConnection();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			if (rs.next()) {
				posId = rs.getInt("posId");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return posId;
	}

}
